﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using System.Data.Entity;
using ThesisSystem.Models;
using ThesisSystem.DAL;
using ThesisSystem.ViewModels;
using System.Web.Helpers;
using System.Data;
namespace ThesisSystem.Controllers
{
    public class AccountController : Controller
    {
        private ThesisSystemEntities db = new ThesisSystemEntities();
        [Authorize]
        public ActionResult Index()
        {
            //用户为教师时
            if (Roles.IsUserInRole("Teachers"))
            {
                //读取教师信息
                var userKey=new Guid(Membership.GetUser().ProviderUserKey.ToString());
                var teacher = db.Teachers
                            .Include(t => t.Department)
                            .Where(t => t.UserID == userKey)
                            .SingleOrDefault();
                if (teacher == null)
                {
                    //如果没有教师信息，则跳转到添加信息页
                    var redirectPage=new RedirectPage(){
                        ActionName="Create",
                        ControllerName="Account",
                        Msg="暂无个人信息，页面将跳转到添加个人信息"
                    };
                    return View("RedirectPage", redirectPage);
                }
                return View("TeacherInfo", teacher);
            }
            //默认用户为学生
            var userID = new Guid(Membership.GetUser().ProviderUserKey.ToString());
            var student = db.Students
                        .Include(s => s.GClass)
                        .Include(s => s.Department)
                        .Where(s => s.UserID == userID)
                        .SingleOrDefault();
            if (student == null)
            {
                //如果没有学生信息，则跳转到添加信息页
                var redirectPage = new RedirectPage()
                {
                    ActionName = "Create",
                    ControllerName = "Account",
                    Msg = "暂无个人信息，页面将跳转到添加个人信息"
                };
                return View("RedirectPage", redirectPage);
            }
            return View("StudentInfo",student);
        }

        public ActionResult Create()
        {
            
            if (Roles.IsUserInRole("Teachers"))
            {
                return RedirectToAction("TeacherCreateInfo");
            }
            return RedirectToAction("StudentCreateInfo");
        }

        public ActionResult TeacherCreateInfo()
        {
            if (Roles.IsUserInRole("Teachers"))
            {
                var sex = new List<string>() { "男", "女" };
                ViewBag.Sex = new SelectList(sex);
                ViewBag.DepartmentID = new SelectList(db.Departments, "DepartmentID", "DepartmentName");
                return View();
            }
            return RedirectToAction("Index");
        }

        [HttpPost]
        public ActionResult TeacherCreateInfo(Teacher teacher)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    teacher.UserID = new Guid(Membership.GetUser().ProviderUserKey.ToString());
                    db.Teachers.Add(teacher);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
            }
            catch (DataException)
            {
                ModelState.AddModelError("", "信息填写不正确，请检查后再保存！");
            }
            var sex = new List<string>() { "男", "女" };
            ViewBag.Sex = new SelectList(sex);
            ViewBag.DepartmentID = new SelectList(db.Departments, "DepartmentID", "DepartmentName");
            return View(teacher);
        }

        public ActionResult StudentCreateInfo()
        {
            if (!Roles.IsUserInRole("Students"))
            {
                return RedirectToAction("Index");
            }
            var sex = new List<string>() { "男", "女" };
            ViewBag.Sex = new SelectList(sex);
            ViewBag.AdmitProfessional = new SelectList(db.Professions, "ProfessionID", "ProfessionName");
            ViewBag.StudyProfessional = ViewBag.AdmitProfessional;
            var educationLevel = new List<String>() { "本科", "专科" };
            ViewBag.EducationLevel = new SelectList(educationLevel);
            ViewBag.ClassID = new SelectList(db.GClasses, "ClassID", "ClassName");
            ViewBag.DepartmentID = new SelectList(db.Departments,"DepartmentID" , "DepartmentName");
            ViewBag.TeacherUserID = new SelectList(db.Teachers, "UserID", "TeacherName");
            return View();
        }

        [HttpPost]
        public ActionResult StudentCreateInfo(Student student,FormCollection collection)
        {
            try
            { 
                if(ModelState.IsValid)
                {
                    //插入学生数据
                    student.UserID = new Guid(Membership.GetUser().ProviderUserKey.ToString());
                    db.Students.Add(student);
                    db.SaveChanges();
                    //保存图片
                    WebImage pic = WebImage.GetImageFromRequest("filePhoto");
                    SaveImage(student.UserID,pic);
                    return RedirectToAction("Index");
                }
            }
            catch(DataException)
            {
                ModelState.AddModelError("", "信息填写不正确，请检查后再保存！");
            }
            var sex = new List<string>() { "男", "女" };
            ViewBag.Sex = new SelectList(sex);
            ViewBag.AdmitProfessional = new SelectList(db.Professions, "ProfessionID", "ProfessionName");
            ViewBag.StudyProfessional = ViewBag.AdmitProfessional;
            var educationLevel = new List<String>() { "本科", "专科" };
            ViewBag.EducationLevel = new SelectList(educationLevel);
            ViewBag.GClassID = new SelectList(db.GClasses, "ClassID", "ClassName");
            ViewBag.DepartmentID = new SelectList(db.Departments, "DepartmentID", "DepartmentName");
            ViewBag.TeacherUserID = new SelectList(db.Teachers, "UserID", "TeacherName");
            return View("StudentCreateInfo");
        }

        /// <summary>
        /// 保存照片，仅能上传jpg
        /// </summary>
        /// <param name="userID">用户ID</param>
        /// <param name="pic">WebImage对象</param>
        private void SaveImage(Guid userID, WebImage pic)
        {
            if (pic != null)
            {
                pic = pic.Resize(90,120, preventEnlarge: true);
                var imgFile = userID.ToString() + ".jpg";
                var picPath = Server.MapPath("~/Content/Photos/" + imgFile);
                pic.Save(picPath, forceCorrectExtension: false);
            }
        }

        /// <summary>
        /// 上传照片页面
        /// </summary>
        /// <returns></returns>
        public ActionResult UploadPhoto()
        {
            return View();
        }

        [HttpPost]
        public ActionResult UploadPhoto(FormCollection collection)
        {
            var userID = new Guid(Membership.GetUser().ProviderUserKey.ToString());
            WebImage pic = WebImage.GetImageFromRequest("filePhoto");
            SaveImage(userID, pic);
            return View();
        }

        public ActionResult Edit()
        {
            if (Roles.IsUserInRole("Teachers"))
            {
                var teacherUserID = new Guid(Membership.GetUser().ProviderUserKey.ToString());
                var teacher=db.Teachers
                            .Include(t => t.Department)
                            .Where(t => t.UserID == teacherUserID)
                            .SingleOrDefault();
                if (teacher == null)
                {
                    return RedirectToAction("Index");
                }
                var tsex = new List<string>() { "男", "女" };
                ViewBag.Sex = new SelectList(tsex, teacher.Sex);
                ViewBag.DepartmentID = new SelectList(db.Departments, "DepartmentID", "DepartmentName", teacher.DepartmentID);
                return View("TeacherEditInfo",teacher);
            }
            var userID = new Guid(Membership.GetUser().ProviderUserKey.ToString());
            var student = db.Students
                        .Include(s => s.GClass)
                        .Include(s => s.Department)
                        .Where(s => s.UserID == userID)
                        .SingleOrDefault();
            if(student==null)
            {
                return RedirectToAction("Index");
            }
            var sex = new List<string>() { "男", "女" };
            ViewBag.Sex = new SelectList(sex,student.Sex);
            ViewBag.AdmitProfessional = new SelectList(db.Professions, "ProfessionID", "ProfessionName",student.AdmitProfessional);
            ViewBag.StudyProfessional = ViewBag.AdmitProfessional;
            var educationLevel = new List<String>() { "本科", "专科" };
            ViewBag.EducationLevel = new SelectList(educationLevel,student.EducationLevel);
            ViewBag.GClassID = new SelectList(db.GClasses, "ClassID", "ClassName",student.ClassID);
            ViewBag.Department = new SelectList(db.Departments, "DepartmentID", "DepartmentName",student.DepartmentID);
            ViewBag.TeacherUserID = new SelectList(db.Teachers, "UserID", "TeacherName",student.TeacherUserID);
            return View("StudentEditInfo",student);
        }

        public ActionResult TeacherEditInfo(Teacher teacher)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    teacher.UserID = new Guid(Membership.GetUser().ProviderUserKey.ToString());
                    db.Entry(teacher).State = EntityState.Modified;
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
            }
            catch (DataException)
            {
                ModelState.AddModelError("", "信息填写不正确，请检查后再保存！");
            }
            var tsex = new List<string>() { "男", "女" };
            ViewBag.Sex = new SelectList(tsex, teacher.Sex);
            ViewBag.DepartmentID = new SelectList(db.Departments, "DepartmentID", "DepartmentName", teacher.DepartmentID);
            return View(teacher);
        }

        public ActionResult Info()
        {
            return View();
        }

        //
        // GET: /Account/LogOn
        public ActionResult LogOn()
        {
            return View();
        }

        //
        // POST: /Account/LogOn

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }

        //
        // GET: /Account/Register

        public ActionResult Register()
        {
            return View();
        }

        //
        // POST: /Account/Register

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus;
                Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
                    //用户默认添加到学生组
                    Roles.AddUserToRole(model.UserName, "Students");
                    return Content("注册成功");
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePassword

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        //
        // POST: /Account/ChangePassword

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {

                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded;
                try
                {
                    MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
                    changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePasswordSuccess

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion

        public ActionResult UserInfo()
        {
            ViewBag.UserName = User.Identity.Name;
            var role = Roles.GetRolesForUser().Count()!=0?Roles.GetRolesForUser()[0]:"";
            switch (role)
            {
                case "Administrators":
                    ViewBag.Role = "管理员";
                    break;
                case "Teachers":
                    ViewBag.Role = "教师";
                    break;
                default:
                    ViewBag.Role = "学生";
                    break;
            }
            return View();
        }
    }
}
